/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package assignment3;

/**
 *
 * @author Burhan
 */
public class SubstitutionChipher implements MessageDecoder, MessageEncoder{

    private int shift;

    public SubstitutionChipher(int shift)throws NumberFormatException {
        this.shift = shift%95;
    }

    public String decode(String cipherText)
    {
        char[] text = new char[cipherText.length()];
        cipherText.getChars(0, cipherText.length(), text, 0);

        for(int i = 0;i<text.length;i++)
        {
            char temp = text[i];
            if(temp-shift<32)
            {
                text[i] = (char) (127-(32-(temp - shift)));
            }
            else
            {
                text[i] = (char) (temp-shift);
            }

        }
        
        String decodedText = new String(text);
        return decodedText;

    }

    public String encode(String plainText)
    {
        char[] text = new char[plainText.length()];
        plainText.getChars(0, plainText.length(), text, 0);

        for(int i = 0;i<text.length;i++)
        {
            char temp = text[i];
            if(temp+shift>126)
            {
                text[i] = (char) (((temp + shift)-126)+31);
            }
            else
            {
                text[i] = (char) (temp+shift);
            }

        }
        String encodedText = new String(text);
        return encodedText;
    }
}
